package com.atguigu.lease.web.app.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.common.utils.VerifyCodeUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.SmsService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private SmsService smsService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserInfoService userInfoService;

    @Override
    public void getCode(String phone) {
        if(!StringUtils.hasLength(phone)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        //1.准备数据
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        //String code = 1000000 + new Random().nextInt(9999999) + "".substring(0,7);

        //查找redis中是否有短时间内请求的验证码数据，如果有表明用户频繁获取验证码，应返回报错拒绝请求
        if(redisTemplate.hasKey(key)){
         throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
        }

        //2.生成验证码
        String code = VerifyCodeUtil.getVerifyCode(6);

        //todo 3.发送验证码 // 执行此行花钱
        smsService.sendCode(phone,code);
        //4.保存验证码
        redisTemplate.opsForValue().set(key,code,RedisConstant.APP_LOGIN_CODE_TTL_SEC,TimeUnit.SECONDS);
    }

    @Override
    public String login(LoginVo loginVo) {
        //用户是否填写手机号
        if(!StringUtils.hasLength(loginVo.getPhone())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        //校验验证码是否为空
        if(!StringUtils.hasLength(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }

        //通过redis校验验证码是否存在，用于判断用户登录是的验证码是否过期
        String userKey = RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone();
        if(!redisTemplate.hasKey(userKey)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
        //判断用户输入的验证码是否正确
        if(!redisTemplate.opsForValue().get(userKey).equals(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        //用户输入的验证码正确，之后查询数据库是否有该用户 loginVo.getPhone()
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getPhone, loginVo.getPhone());
        UserInfo userInfo = userInfoService.getOne(queryWrapper);

        //若无该用户则创建该用户并保存到数据库中
        if(userInfo == null){
            UserInfo info = new UserInfo();
            info.setPhone(loginVo.getPhone())
                    .setNickname("尚庭用户" + loginVo.getPhone())
                    .setAvatarUrl("http://192.168.126.128:9000/lease/2024/04/title.jpg")
                    .setStatus(BaseStatus.ENABLE);
            userInfoService.save(info);
        }

        //已查到用户信息，校验用户状态是否能正常使用，即非禁用状态
        if(userInfo.getStatus().equals(BaseStatus.DISABLE)){
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }

        //用查到的用户对象生成token
        return JwtUtil.createToken(userInfo.getId());
    }
}
